package com.wdl.modules.myhouse.controller.sys;

import com.wdl.modules.myhouse.dto.UserDTO;
import com.wdl.modules.myhouse.entity.UserEntity;
import com.wdl.modules.myhouse.service.UserService;
import com.wdl.modules.myhouse.common.Constant;
import com.wdl.modules.myhouse.common.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * @author 昏昏的君
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户详细信息")
@Slf4j
public class SysUserDescribeController {

    @Autowired
    private UserService userService;


    @GetMapping("/all")
    public Result<List<UserDTO>> allUser() {
        List<UserEntity> entities = userService.list();
        ArrayList<UserDTO> dtos = new ArrayList<>();
        for (UserEntity entity:entities){
            UserDTO dto = new UserDTO();
            BeanUtils.copyProperties(entity,dto);
            dtos.add(dto);
        }
        return new Result<List<UserDTO>>().ok(dtos);
    }

    @GetMapping("/del/{id}")
    public Result<List<UserDTO>> delUser(@PathVariable("id")String id) {
        userService.removeById(id);
        return new Result<List<UserDTO>>().ok();
    }

    @PostMapping("/update/{id}")
    public Result<List<UserDTO>> updateUser(@PathVariable("id")String id,UserDTO user) {
        UserEntity entity = new UserEntity();
        BeanUtils.copyProperties(user,entity);
        try {
            FileInputStream in = new FileInputStream(Constant.HEAD_STORAGE_ADDR + id + ".jpg");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            int len=0;
            while ((len=in.read(buffer) )!=-1){
               out.write(buffer,0,len);
            }
            byte[] bytes = out.toByteArray();
            entity.setAvatar(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        userService.updateById(entity);
        return new Result<List<UserDTO>>().ok();
    }

    @PostMapping("/uploadAvatar")
    public Result<String> uploadAvatar(@RequestParam("avatar") MultipartFile file,@RequestParam("userId") String userId){
        try {
            System.out.println("userId"+userId);
            String filename = file.getOriginalFilename();
            String suffix = file.getOriginalFilename().substring(filename.lastIndexOf("."));
            file.transferTo(new File(Constant.HEAD_STORAGE_ADDR+userId+suffix));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result<String>().ok(file.getOriginalFilename());
    }


}
